package cn.hwh.springframework.beans.factory.support;

import cn.hwh.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.util.Objects;

/**
 * @author wenhao hu
 * @title: AbstractAutowireCapableBeanFactory
 * @projectName mini-spring
 * @description: TODO
 * @date 2022/1/2411:47
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{

    /**
     * 使用CGlib的实例化方式
     */
    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();


    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object ...args) {
        Object bean = createBeanInstance(beanName,beanDefinition,args);
        addSingleton(beanName,bean);
        return bean;
    }

    protected Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] objects){
        Constructor constructorToUse = null;
        //获取容器内实例的信息
        Class beanClass = beanDefinition.getBeanClass();
        //获取容器内实例的全部构造方法
        Constructor[] declaredConstructors = beanClass.getDeclaredConstructors();
        //循环构造方法，找到一个参数个数和objects相同的构造方法
        for (Constructor ctor : declaredConstructors) {
            //这里只是简单比较一下参数个数，实际上要考虑参数类型等问题
            if (null != objects && ctor.getParameterTypes().length == objects.length) {
                //将该构造方法保存
                constructorToUse = ctor;
                break;
            }
        }
        //创建构造方法
        return instantiationStrategy.instantiate(beanDefinition,beanName,constructorToUse,objects);
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
